import $ from 'jquery'
// 封装ajax
var request = (url, type = "get", data = "", header, async = true) => {
  // console.log(header);
  var headers = {};

  switch (header) {
    case 1:
      headers["Content-Type"] = "application/x-www-form-urlencoded";//post提交表单  key1=val1&key2=val2 的方式进行编码
      headers["Authorization"] = sessionStorage.getItem("token")
      break;
    case 2:
      headers["Content-Type"] = "multipart/form-data";//post提交表单  上传文件时使用
      break;
    case 3:
      headers["Content-Type"] = "text/xml";//用于xml的数据交换格式
      break;
    case 4:
      headers["Content-Type"] = "application/json";//向后端传递json字符串
      data = JSON.stringify(data);
      break;
  }
  var option = {
    type,
    url,
    data,
    async,
    // headers,
  }
  if (header) {//如果给header传参了
    // console.log("进来");
    option.headers = headers;
  }
  // console.log(option);
  return new Promise((resolve, reject) => {
    $.ajax({
      ...option,
      success (res) {
        resolve(res);
      },
      error (err) {
        reject(err)
      }
    })
  })
}
export {request}
